

from datetime import datetime
from typing import Literal, Optional
from flask import Blueprint, jsonify, request
from pydantic import BaseModel, field_validator
from enum import Enum

from app.models.task_enum import TaskStatus
from app.models.task_model import TaskListQueryModel, TaskModel
from app.services.task_service import TaskService
from ..database import mongodb
import app.utils.response_utils as res_utils

import flask_pydantic as fpyd

tasks_bp = Blueprint('tasks', __name__)

task_service = TaskService()


@tasks_bp.route('/list', methods=['GET'])
def get_tasks():

    # data = request.get_json()

    data = request.args.to_dict()

    # print(f"Received data: {data}")

    # 处理查询参数
    try:
        if not data:
            query = TaskListQueryModel()  # 使用默认值
        else:
            query = TaskListQueryModel(**data)
        # print(f"Parsed query: {query.status}")
    except ValueError as e:
        return jsonify({"message": f"Invalid query parameter: {str(e)}"}), 400

    tasks = task_service.get_all_tasks(query=query)


    tasks = res_utils.format_list_response(tasks)

    return jsonify({"data": tasks})


@tasks_bp.route('/delete_task/<int:task_id>', methods=['POST'])
def delete_task(task_id):
    is_success = task_service.delete_task_by_id(task_id)

    if not is_success:
        return jsonify({"message": "Task not found"})

    return jsonify({"message": "Task deleted successfully"})


@tasks_bp.route('/add_task', methods=['POST'])
def create_task():
    
    data = request.get_json()
    
    # 基本数据验证
    if not data:
        return jsonify({"message": "No data provided"}), 400
    
    if not data.get("title", "").strip():
        return jsonify({"message": "Title is required"}), 400
    
    new_task = {
        "title": data.get("title", "").strip(),
        "description": data.get("description", ""),
        "status": TaskStatus.PENDING.value,  # 使用枚举的值
        "created_at": datetime.now(),
        "updated_at": datetime.now()
    }
    
    try:
        # 实际保存到数据库
        result = mongodb.tasks.insert_one(new_task)
        
        # 返回创建的任务信息
        created_task = mongodb.tasks.find_one({"_id": result.inserted_id})
        if created_task:
            created_task["_id"] = str(created_task["_id"])  # 转换ObjectId为字符串
        
        return jsonify({
            'success': True,
            'message': 'Task created successfully',
            'task': created_task,
            'task_id': str(result.inserted_id)
        }), 201
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'Failed to create task: {str(e)}'
        }), 500



@tasks_bp.route('/update_task/<task_id>', methods=['POST'])
def update_task(task_id):
    """更新任务 - 支持部分更新"""
    from app.models.task_model import UpdateTaskModel
    
    try:
        data = request.get_json()
        if not data:
            return jsonify({"message": "No data provided"}), 400
        
        # 使用 Pydantic 验证更新数据
        update_model = UpdateTaskModel(**data)
        
        # 检查是否有实际更新
        if not update_model.has_updates():
            return jsonify({"message": "No fields to update"}), 400
        
        # 获取更新字典（排除 None 值）
        update_data = update_model.get_update_dict(exclude_none=True)
        
        print(f"更新任务 {task_id}: {update_data}")
        
        # 调用服务更新任务
        updated_task = task_service.update_task(task_id, update_data)

        if not updated_task:
            return jsonify({"message": "Task not found"}), 404
        
        return jsonify({
            "message": "Task updated successfully",
            "updated_fields": list(update_data.keys())
        })
        
    except ValueError as e:
        return jsonify({"message": f"Validation error: {str(e)}"}), 400
    except Exception as e:
        return jsonify({"message": f"Server error: {str(e)}"}), 500
